/*
    RExLib project, file utcpserver.h
    Copyright (C) 2012  Sarvaritdinov Ravil ra9oaj@gmail.com

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/


#ifndef UTCPSERVER_H
#define UTCPSERVER_H

#include "rabstractsocket.h"
#include "rtcpsocket.h"
#include <stdio.h>
#include <sys/epoll.h>
#include <malloc.h>

namespace rex{

class RServer
{

public:
    enum Errors {
        SE_CREATESOCKET,
	SE_BIND,
        SE_LISTEN,
        SE_EPOOL,
	SE_AF,
	SE_PF,
        SE_INTERNAL
    };

    RServer();
    virtual ~RServer();

    bool listenHostPort(char *host, uint16_t port = 0);
    bool isListening() const;
    void setMaxClients(int max);
    void setAddressFamily(RAbstractSocket::AddressFamily af);
    void setProtocolFamily(RAbstractSocket::ProtocolFamyly pf);
    char* serverHost() const;
    uint16_t serverPort() const;
    int maxClients() const;
    int socketDescriptor() const;
    void stop();
    int error() const;

protected:
    virtual void addedNewClient(int socfd);
    virtual void canReadData(int socfd);
    virtual void canWriteData(int socfd);

    void setListStatus(bool state);
    void setErrorCode(int ecode);

    RAbstractSocket *insoc;

private:
    void mainloop();

    char* _host;
    uint16_t _port;
    bool _list_state;
    bool _stop_flag;
    int _errno;
    int _max_clnt;
    int efd;
    int _af,_pf;
    struct addrinfo hints;
    struct epoll_event event;
    struct epoll_event *events;
};

}
#endif // UTCPSERVER_H
